var express = require('express');
const Result = require('../lib/Result');
const Manager = require('../db/models/manager/manager');
var router = express.Router();
//获取管理员列表
router.get("/:page", (req, res) => {
    let token = req.auth.id;
    let page = req.params.page;
    let limit = req.body.limit ? req.body.limit : 10;
    Manager.getAll(limit, page).then(row => {
        let list = { list: [] }
        row.forEach(value => {
            list.list.push(value.toJSON())
        })
        res.json(Result.success(list))
    })
})
//修改管理员
router.post("/:id", (req, res) => {
    let token = req.auth;
    if (token.super != 1) {
        return res.json(Result.permissionDenied())
    }
    Manager.update({
        username: req.body.username,
        password: req.body.password,
        role_id: req.body.role_id,
        status: req.body.status,
        avatar: req.body.avatar
    }, {
        where: {
            id: req.params.id
        }
    }).then(value => {
        res.json(Result.success())
    }).catch(err => {
        res.json(Result.validateFailed(err.message))
    })
})
//添加管理员
router.post("", (req, res) => {
    let token = req.auth.id;
    if (token.super != "1") {
        return res.json(Result.permissionDenied())
    }
    Manager.create(req.body).then(value => {
        res.json(Result.success(value.toJSON()))
    }).catch(err => {
        res.json(Result.validateFailed())
    })
})
//删除管理员
router.post("/:id/delete",(req,res)=>{
    let token = req.auth.id;
    if (token.super != "1") {
        return res.json(Result.permissionDenied())
    }
    if (token.id==req.params.id) {
        return res.json(Result.validateFailed("不能删除自己"))
    }
    Manager.delectById(req.params.id).then((value)=>{
        if (value>0) {
            res.json(Result.success())
        } else {
            res.json(Result.validateFailed("不存在的ID"))
        }
    }
    ).catch(err=>{
        res.json(Result.validateFailed(err.message))
    })
    
})
/**
 * 修改管理员状态
 */
router.post("/:id/update_status",(req,res)=>{
    let token = req.auth.id;
    if (token.super!=1) {
        return res.json(Result.permissionDenied())
    }
    if(token.id==req.params.id){
        return res.json(Result.validateFailed("不允许设置自己的状态"))
    }
    Manager.updateStatus(req.params.id,req.body.status).catch(
        res.json(Result.success())
    ).catch(err=>{
        res.json(Result.validateFailed(err.message))
    })
})
module.exports = router;